package com.android.inestpin.adapt;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;


import com.android.inestpin.R;
import com.android.inestpin.activity.GoodsDetailActivity2;
import com.android.inestpin.activity.ProductCartActivity;
import com.android.inestpin.model.ajaxcartCallback;
import com.android.inestpin.model.ajaxcartdata;
import com.android.inestpin.model.detail.addtocartCallback;
import com.android.inestpin.model.detail.addtocartdata;
import com.android.inestpin.utils.ConstantsUrl;
import com.android.inestpin.utils.HttpUtils;
import com.android.inestpin.utils.ObjectUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;


public class CartAdapter extends BaseAdapter {

    private Context context;
    private List<HashMap<String,String>> dataList;
    private ViewHolder vh;
    private Map<String,Integer> pitchOnMap;
    private RefreshPriceInterface refreshPriceInterface;
    private boolean isUpdateCart=false;



    public CartAdapter(Context context, List<HashMap<String,String>> list){
        this.context=context;
        this.dataList=list;

        pitchOnMap=new HashMap<>();
        for(int i=0;i<dataList.size();i++){
            pitchOnMap.put(dataList.get(i).get("id"),0);
        }
    }
    public CartAdapter(Context context, List<HashMap<String,String>> list, boolean isUpdateCart){
        this.context=context;
        this.dataList=list;
        this.isUpdateCart=isUpdateCart;

        pitchOnMap=new HashMap<>();
        for(int i=0;i<dataList.size();i++){
            pitchOnMap.put(dataList.get(i).get("id"),0);
        }
    }
    @Override
    public View getView(final int position, View view, ViewGroup viewGroup) {
        vh=new ViewHolder();

        if(view==null){
            view= LayoutInflater.from(context).inflate(R.layout.item_shopcart_product,null);

            vh.checkBox=(CheckBox)view.findViewById(R.id.check_box);
            vh.icon=(ImageView)view.findViewById(R.id.iv_adapter_list_pic);
            vh.name=(TextView)view.findViewById(R.id.tv_goods_name);
            vh.price=(TextView)view.findViewById(R.id.tv_goods_price);
            vh.type=(TextView)view.findViewById(R.id.tv_type_size);
            vh.num=(TextView)view.findViewById(R.id.tv_num);
            vh.reduce=(TextView)view.findViewById(R.id.tv_reduce);
            vh.add=(TextView)view.findViewById(R.id.tv_add);

            view.setTag(vh);
        }else {
            vh=(ViewHolder)view.getTag();
        }

        if(isUpdateCart){
            vh.add.setVisibility(View.GONE);
            vh.reduce.setVisibility(View.GONE);
        }else{
            vh.add.setVisibility(View.VISIBLE);
            vh.reduce.setVisibility(View.VISIBLE);
        }

        if(dataList.size()>0){

            if(pitchOnMap.get(dataList.get(position).get("id"))==0)vh.checkBox.setChecked(false);
            else vh.checkBox.setChecked(true);
            final HashMap<String,String> map=dataList.get(position);
            vh.name.setText(map.get("name"));
            vh.num.setText(map.get("count"));
//            vh.type.setText(map.get("type"));
            vh.type.setText("￥ "+(Double.valueOf(map.get("type")) ));
            vh.type.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); // 中划线
            if(map.get("price")!=null){
                vh.price.setText("￥ "+(Double.valueOf(map.get("price")) ));
            }else{
                vh.price.setText("￥ "+(0.00 ));
            }

            ObjectUtils.photo(context, map.get("imgsrc"),vh.icon );
            vh.name.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent=new Intent(context, GoodsDetailActivity2.class);
                    intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_ID, map.get("goods_id"));
                    context.startActivity(intent);
                }
            });
            vh.icon.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent=new Intent(context, GoodsDetailActivity2.class);
                    intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_ID, map.get("goods_id"));
                    context.startActivity(intent);
                }
            });
            vh.checkBox.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    final int index=position;
//                    ajaxCartGoods(dataList.get(index).get("goods_id"));
                    if(((CheckBox)view).isChecked()){
                        pitchOnMap.put(dataList.get(index).get("id"),1);
  //  MyLog.e("inest","dataList.get(index).get(\"id\")="+dataList.get(index).get("id"));
                    }else{
                        pitchOnMap.put(dataList.get(index).get("id"),0);

                    }
                    refreshPriceInterface.refreshPrice(pitchOnMap);

                }
            });
            vh.reduce.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    final int index=position;
                    dataList.get(index).put("count",(Integer.valueOf(dataList.get(index).get("count"))-1)+"");
                    if(Integer.valueOf(dataList.get(index).get("count"))<=0){
                        //可提示是否删除该商品,确定就remove,否则就保留1
                        if(Integer.valueOf(dataList.get(index).get("count"))==1){

                        }else{
                            String deID=dataList.get(index).get("id");
                            dataList.remove(index);
                            pitchOnMap.remove(deID);
                        }

                    }
                    Handler handler=new Handler();
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            delCart(dataList.get(index).get("goods_id"));
                        }
                    },100);

                    notifyDataSetChanged();
                    refreshPriceInterface.refreshPrice(pitchOnMap);
                }
            });
            vh.add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    final int index=position;
                    dataList.get(index).put("count",(Integer.valueOf(dataList.get(index).get("count"))+1)+"");
                    Handler handler=new Handler();
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            addToCart(dataList.get(index).get("goods_id"));
                        }
                    },100);

                    notifyDataSetChanged();
                    refreshPriceInterface.refreshPrice(pitchOnMap);
                }
            });

        }

        return view;
    }

    public Map<String,Integer> getPitchOnMap(){
        return pitchOnMap;
    }
    public void setPitchOnMap(Map<String,Integer> pitchOnMap){
        this.pitchOnMap=new HashMap<>();
        this.pitchOnMap.putAll(pitchOnMap);
    }

    public interface RefreshPriceInterface{
        void refreshPrice(Map<String, Integer> pitchOnMap);
//        void refreshSelectgoodIds(ArrayList<String> SelectgoodIdsList);
    }
    public void setRefreshPriceInterface(RefreshPriceInterface refreshPriceInterface){
        this.refreshPriceInterface=refreshPriceInterface;
    }

    @Override
    public Object getItem(int i) {

        return vh.checkBox.isChecked();
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public int getCount() {
        if (dataList != null) {
            return dataList.size();
        } else {
            return 0;
        }
    }

    class ViewHolder{
        CheckBox checkBox;
        ImageView icon;
        TextView name,price,num,type,reduce,add;
    }
    //添加至购物车
    public void addToCart(String id){
        String address = ConstantsUrl.domain + "order/addtocart";
        HashMap<String, String> map = new HashMap<>();
        HashMap<String, String> header = new HashMap<>();

        map.put("qty", "1");
        map.put("id", id);

//        map.put("act", phone);
//        map.put("spec", useraddress);


        HttpUtils.post(address, null, map, new addtocartCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {
//                MyLog.e("inest","response="+e.getMessage());
            }

            @Override
            public void onResponse(addtocartdata response, int id) {
//                MyLog.e("inest","response="+response.getData().getRes().getSubtotal() );
//                Toast.makeText(mcontext,"添加购物车成功",Toast.LENGTH_LONG).show();
                ((ProductCartActivity)context).isNeedFinish=true;
                Intent intent=new Intent(context,ProductCartActivity.class);
                context.startActivity(intent);
            }
        });
    }


    public void delCart(String id){
        String address = ConstantsUrl.domain + "order/del_cart";
        HashMap<String, String> map = new HashMap<>();
        map.put("ids", id);


        HttpUtils.get(address, null, map, new ajaxcartCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(ajaxcartdata response, int id) {
                ((ProductCartActivity)context).isNeedFinish=true;
                Intent intent=new Intent(context,ProductCartActivity.class);
                context.startActivity(intent);
            }
        });
    }
    public void ajaxCartGoods(String address_id){
        String address= ConstantsUrl.domain + "order/ajax_cart";
        HashMap<String, String> map = new HashMap<>();
        map.put("address_id",address_id);
        map.put("express_id","1");

        HttpUtils.get(address, null, map, new ajaxcartCallback() {


            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(ajaxcartdata response, int id) {

            }
        });

    }
}
